let crypto = require('crypto');
let { api_key } = require('../weChat/config');

// 获取express 的req 返回一个客户端的ip
const getClientIp = req => {
  let ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
  // 如果是双卡双待, 要确定哪个才是真正的ip地址
  return ip.split(',')[0];
};

// 将微信返回的xml对象格式一下
const formatXmlObj = obj=> {

  let newObj = {};

  for ( let key in obj ) {
    if ( obj.hasOwnProperty( key ) ) {
      if ( Object.prototype.toString.call( obj[ key ] ) === '[object Array]' ){
        newObj[key] = obj[ key ][ 0 ];
      }
    }

  }


  return newObj;
};

// 根据签名算法产生签名
const getSign = obj => {

  let temArr = Object.keys(obj);

  // 对临时数组进行排序
  temArr.sort();

  let temStr = temArr
    .map( el => el + '=' + obj[el] )
    .join( '&' );

  // 拼接商户api密钥
  temStr += '&key=' + api_key;

  // 进行md5签
  return crypto.createHash('md5').update(temStr,'utf8').digest('hex').toUpperCase();
};


module.exports = {
  getClientIp,
  formatXmlObj,
  getSign
};